package com.ocom.payconfig.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.entity.card.EntityScaleUpgrade;
import com.ocom.common.entity.card.EntityUpgradePlan;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.webapi.scaleupgrade.*;
import com.ocom.payconfig.service.ScaleUpgradeService;
import com.ocom.payconfig.service.UpgradePlanService;
import com.ocom.redis.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ScaleUpgradeController {

    @Autowired
    private ScaleUpgradeService scaleUpgradeService;
    @Autowired
    private UpgradePlanService upgradePlanService;
    @Resource
    RedisUtil redisUtil;


    @PostMapping(PayConfigUrl.Url_getScaleUpgradeStatus)
    public Result getScaleUpgradeStatus(@RequestBody ScaleUpgradeOnShowRequest request) {
        Object o = redisUtil.get("ScaleUpgradeStatus:" + request.getUpgradeCode());
        List<EntityUpgradePlan> upgradeCodeList = null;
        if (null != o) {
            upgradeCodeList = JSON.parseArray(JSON.toJSONString(o), EntityUpgradePlan.class);
        } else {
            upgradeCodeList = upgradePlanService.findListByUpgradeCode(request.getUpgradeCode());
            if (null == upgradeCodeList || 0 == upgradeCodeList.size()) {
                return ResultUtil.error(ResultEnum.Err_4211);
            }
            redisUtil.set("ScaleUpgradeStatus:" + request.getUpgradeCode(), upgradeCodeList, 4 * 60 * 60l);
        }

        GetScaleUpgradeStatusResponse response = new GetScaleUpgradeStatusResponse();
        for (EntityUpgradePlan entityUpgradePlan : upgradeCodeList) {
            String[] upgradeComIds = entityUpgradePlan.getUpgradeComids().split(",");
            String[] backComIds = entityUpgradePlan.getBackComids().split(",");
            if (check(upgradeComIds, request.getComId()) && !check(backComIds, request.getComId())) {
                response.setUpgradeStatus(1);
                break;
            } else if (check(backComIds, request.getComId())) {
                response.setUpgradeStatus(0);
                break;
            } else {
                response.setUpgradeStatus(0);
            }
        }

        return ResultUtil.success(response);
    }

    private static boolean check(String[] targets, Integer comId) {
        boolean result = false;
        try {
            for (String target : targets) {
                if (target.startsWith(">=")) {
                    if (comId >= Integer.parseInt(target.substring(2))) {
                        result = true;
                    }
                } else if (target.startsWith("<=")) {
                    if (comId <= Integer.parseInt(target.substring(2))) {
                        result = true;
                    }
                } else if (target.startsWith(">")) {
                    if (comId > Integer.parseInt(target.substring(1))) {
                        result = true;
                    }
                } else if (target.startsWith("<")) {
                    if (comId < Integer.parseInt(target.substring(1))) {
                        result = true;
                    }
                } else if (target.contains("-")) {
                    String[] between = target.split("-");
                    if (2 == between.length) {
                        if (comId >= Integer.parseInt(between[0]) && comId <= Integer.parseInt(between[1])) {
                            result = true;
                        }
                    }
                } else if (comId == Integer.parseInt(target)) {
                    result = true;
                }
                if (result) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @PostMapping(PayConfigUrl.Url_getUpgradeCodeList)
    public Result getUpgradeCodeList(@RequestBody ScaleUpgradeOnShowRequest request) {
        Date date = DateUtil.addDays(new Date(), -365);
        PageInfo<EntityScaleUpgrade> upgradeCodeList = scaleUpgradeService.getUpgradeCodeList(date, request.getUpgradeCode(), request.getDescription(), request.getPage(), request.getSize());
        Map<String, Object> map = new HashMap<>();
        map.put("total", upgradeCodeList.getTotal());
        map.put("list", upgradeCodeList.getList());
        return ResultUtil.success(map);
    }

    @PostMapping(PayConfigUrl.Url_newUpgradeCode)
    public Result newUpgradeCode(@RequestBody ScaleUpgradeAddRequest request) {
        EntityScaleUpgrade upgradeCode = scaleUpgradeService.findByUpgradeCode(request.getUpgradeCode(),request.getMsVer());
        if (null != upgradeCode) {
            return ResultUtil.error(ResultEnum.Err_4210);
        }
        upgradeCode = JSON.parseObject(JSON.toJSONString(request), EntityScaleUpgrade.class);
        return ResultUtil.success(scaleUpgradeService.save(upgradeCode));
    }

    @PostMapping(PayConfigUrl.Url_updateUpgradeCode)
    public Result updateUpgradeCode(@RequestBody ScaleUpgradeModifyRequest request) {
        EntityScaleUpgrade upgradeCode = scaleUpgradeService.findByUpgradeCode(request.getUpgradeCode(),request.getMsVer());
        if (null == upgradeCode) {
            return ResultUtil.error(ResultEnum.Err_4211);
        }
        upgradeCode.setDescription(request.getDescription());
        upgradeCode.setMsName(request.getMsName());
//        upgradeCode.setMsVer(request.getMsVer());
        upgradeCode.setModuleName(request.getModuleName());
        upgradeCode.setResult(request.getResult());
        return ResultUtil.success(scaleUpgradeService.update(upgradeCode));
    }

    @PostMapping(PayConfigUrl.Url_startUpgradeCode)
    public Result startUpgradeCode(@RequestBody ScaleUpgradeModifyRequest request) {
        EntityScaleUpgrade upgradeCode = scaleUpgradeService.findByUpgradeCode(request.getUpgradeCode(),request.getMsVer());
        if (null == upgradeCode) {
            return ResultUtil.error(ResultEnum.Err_4211);
        }
        upgradeCode.setBeginTime(new Date());
        upgradeCode.setStatus(1);
        return ResultUtil.success(scaleUpgradeService.update(upgradeCode));
    }

    @PostMapping(PayConfigUrl.Url_stopUpgradeCode)
    public Result stopUpgradeCode(@RequestBody ScaleUpgradePlanRequest request) {
        EntityScaleUpgrade upgradeCode = scaleUpgradeService.findByUpgradeCode(request.getUpgradeCode(),request.getMsVer());
        if (null == upgradeCode) {
            return ResultUtil.error(ResultEnum.Err_4211);
        }
        upgradeCode.setEndTime(new Date());
        upgradeCode.setStatus(request.getStopMode());
        return ResultUtil.success(scaleUpgradeService.update(upgradeCode));
    }

    @PostMapping(PayConfigUrl.Url_getUpgradeCodePlan)
    public Result getUpgradeCodePlan(@RequestBody ScaleUpgradePlanRequest request) {
        return ResultUtil.success(upgradePlanService.findListByUpgradeCode(request.getUpgradeCode()));
    }

    @PostMapping(PayConfigUrl.Url_setUpgradeCodePlan)
    public Result setUpgradeCodePlan(@RequestBody ScaleUpgradePlanRequest request) {
        EntityScaleUpgrade upgradeCode = scaleUpgradeService.findByUpgradeCode(request.getUpgradeCode(),request.getMsVer());
        if (null == upgradeCode) {
            return ResultUtil.error(ResultEnum.Err_4211);
        }
        EntityUpgradePlan entityUpgradePlan = JSON.parseObject(JSON.toJSONString(request), EntityUpgradePlan.class);
        entityUpgradePlan.setPlanTime(new Date());
        upgradePlanService.save(entityUpgradePlan);

        redisUtil.dels("ScaleUpgradeStatus:" + request.getUpgradeCode().substring(0,8));
        return ResultUtil.success();
    }
}
